﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Http;
using System.Web.Http;
using TaDMS.Commons;
using TaDMS.Models;

namespace TaDMS.Controllers
{
    [Authorize(Roles = "Admin, Editer, PhoPhong, ToTruong, NhanVien")]
    public class ApiReportController : ApiController
    {
        private readonly UnitOfWork _unitOfWork = new UnitOfWork();

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetAll()
        {
            var currentUsername = User.Identity.Name;
            var currentUserId = LoginHelper.GetCurrentUserId(currentUsername);
            if (currentUserId == null)
            {
                var error = new
                {
                    success = false,
                    message = "Không tìm được Mã nhân viên của tài khoản: " + currentUsername
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            int? total;
            var employees = _unitOfWork.ReportRepository.GetData(out total, orderBy: order => order.OrderBy(v => v.CreateDate), filter: p => p.EmployeeId == currentUserId);

            if (String.IsNullOrEmpty(_unitOfWork.ReportRepository.ErrorMessage))
            {
                var enumerable = employees as IList<Report> ?? employees.ToList();
                if (enumerable.Any())
                {
                    var result = new
                    {
                        total = total,
                        success = true,
                        message = "success",
                        data = enumerable
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, result);
                }

                var empty = new
                {
                    success = true,
                    message = "empty"
                };
                return Request.CreateResponse(HttpStatusCode.OK, empty);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = _unitOfWork.EmployeeRepository.ErrorMessage
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage ViewReport(string startDate, string endDate)
        {
            var currentUsername = User.Identity.Name;
            var currentUserId = LoginHelper.GetCurrentUserId(currentUsername);
            if (currentUserId == null)
            {
                var error = new
                {
                    success = false,
                    message = "Không tìm được Mã nhân viên của tài khoản: " + currentUsername
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            int? total;
            var employees = _unitOfWork.ReportRepository.GetData(out total, orderBy: o => o.OrderBy(v => v.CreateDate), isPaging: false, filter: p => p.EmployeeId == currentUserId, includeProperties: "Employee");

            if (String.IsNullOrEmpty(_unitOfWork.ReportRepository.ErrorMessage))
            {
                //var enumerable = employees as IList<Report> ?? employees.ToList();
                if (employees.Any())
                {
                    
                    var result = new
                    {
                        total = total,
                        success = true,
                        message = "success",
                        data = employees.ToList()
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, result);
                }

                var empty = new
                {
                    success = true,
                    message = "Reports is empty"
                };
                return Request.CreateResponse(HttpStatusCode.OK, empty);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = _unitOfWork.EmployeeRepository.ErrorMessage
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetReport(DateTime? startDate, DateTime? endDate, string title, int isAll)
        {
            var currentUsername = User.Identity.Name;
            var currentUserId =  LoginHelper.GetCurrentUserId(currentUsername);
            if (currentUserId == null)
            {
                var error = new
                {
                    success = false,
                    message = "Không tìm được Mã nhân viên của tài khoản: " + currentUsername
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            var reports = _unitOfWork.Report.ViewReport(startDate, endDate, title, (int)currentUserId, isAll );

            if (String.IsNullOrEmpty(_unitOfWork.Report.ErrorMessage))
            {
                //var enumerable = employees as IList<Report> ?? employees.ToList();
                if (reports != null && reports.Any())
                {

                    var result = new
                    {
                        total = reports.Count(),
                        success = true,
                        message = "success",
                        data = reports.ToList()
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, result);
                }

                var empty = new
                {
                    success = true,
                    message = "Reports is empty"
                };
                return Request.CreateResponse(HttpStatusCode.OK, empty);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = _unitOfWork.Report.ErrorMessage
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
        }

        [System.Web.Http.HttpPost]
        public HttpResponseMessage Create(Report entity)
        {
            var currentUsername = User.Identity.Name;
            var currentUserId = LoginHelper.GetCurrentUserId(currentUsername);
            if (currentUserId == null)
            {
                var error = new
                {
                    success = false,
                    message = "Không tìm được Mã nhân viên của tài khoản: " + currentUsername
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
            entity.CreateDate = DateTime.Now;
            entity.EmployeeId = currentUserId;
            var result = _unitOfWork.ReportRepository.Create(entity);

            if (result != null && String.IsNullOrEmpty(_unitOfWork.ReportRepository.ErrorMessage))
            {
                var success = new
                {
                    data = result,
                    success = true,
                    message = "Created"
                };
                return Request.CreateResponse(HttpStatusCode.OK, success);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = "Craete false: " + _unitOfWork.ReportRepository.ErrorMessage
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
        }

        [System.Web.Http.HttpPost]
        public HttpResponseMessage Delete(Report entity)
        {
            entity.CreateDate = DateTime.Now;

            var result = _unitOfWork.ReportRepository.Delete(entity);

            if (result != null && String.IsNullOrEmpty(_unitOfWork.ReportRepository.ErrorMessage))
            {
                var success = new
                {
                    data = result,
                    success = true,
                    message = "Deleted"
                };
                return Request.CreateResponse(HttpStatusCode.OK, success);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = "Delete false: " + _unitOfWork.ReportRepository.ErrorMessage
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
        }

        [System.Web.Http.HttpGet]
        [AllowAnonymous]
        public HttpResponseMessage GetListWeek()
        {
            var weeks = DateTimeUtility.WeekInYear(DateTime.Now.Year);

            if (weeks != null)
            {
                if (weeks.Any())
                {
                    var result = new
                    {
                        success = true,
                        message = "success",
                        data = weeks
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, result);
                }

                var empty = new
                {
                    success = false,
                    message = "Error during get info of week"
                };
                return Request.CreateResponse(HttpStatusCode.OK, empty);
            }
            else
            {
                var error = new
                {
                    success = false,
                    message = "Some error"
                };
                return Request.CreateResponse(HttpStatusCode.OK, error);
            }
        }

        [System.Web.Http.HttpGet]
        public HttpResponseMessage GetTitleComboData(int start, int limit, string query)
        {
            int? total;
            var result = String.IsNullOrEmpty(query) || query.Trim().ToUpper().Equals("ALL") ?
                _unitOfWork.Report.GetData(total: out total, isPaging: true, start: start, limit: limit, orderBy: order => order.OrderBy(d => d.ReportTitle)).Where(v => v.ReportTitle != null && !String.IsNullOrEmpty(v.ReportTitle)).Select(v => new { ReportTitle = v.ReportTitle }).Distinct() :
                _unitOfWork.Report.GetData(total: out total, isPaging: true, start: start, limit: limit, orderBy: order => order.OrderBy(d => d.ReportTitle), filter: d => !String.IsNullOrEmpty(d.ReportTitle) && d.ReportTitle.ToUpper().Contains(query.Trim().ToUpper())).Select(v => new { ReportTitle = v.ReportTitle }).Distinct();

            if (String.IsNullOrEmpty(_unitOfWork.Report.ErrorMessage))
            {
                if (total > 0)
                {
                    var success = new
                    {
                        total = total,
                        success = true,
                        data = result.ToList(),
                        message = "success"
                    };
                    return Request.CreateResponse(HttpStatusCode.OK, success);
                }

                var empty = new
                {
                    total = 0,
                    success = true,
                    message = "data is empty"
                };
                return Request.CreateResponse(HttpStatusCode.OK, empty);
            }

            var error = new
            {
                success = false,
                message = "False. " + _unitOfWork.Device.ErrorMessage
            };
            return Request.CreateResponse(HttpStatusCode.OK, error);
        }
    }
}
